//
//  UITextView+MLKit.m
//  TycoonSale
//
//  Created by molon on 15/7/30.
//  Copyright (c) 2015年 molon. All rights reserved.
//

#import "UITextView+MLKit.h"
#import "MLRuntime.h"
#import <objc/runtime.h>
#import "MLKitDefine.h"

static char placeholderColorForTextViewKey;
static char placeholderForTextViewKey;

@implementation UITextView (MLKit)

+ (void)load
{
    Swizzle([self class], @selector(drawRect:), @selector(MLKit_hook_drawRect:));
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewTextChanged:) name:UITextViewTextDidChangeNotification object:nil];
}

+ (void)textViewTextChanged:(NSNotification*)notification
{
    UITextView *textView = CHILD(UITextView, notification.object);
    if (textView.placeholder.length>0) {
        [textView setNeedsDisplay];
    }
}

- (void)MLKit_hook_drawRect:(CGRect)rect
{
    [self MLKit_hook_drawRect:rect];
    
    if (self.text.length<=0) {
        //TODO: 其实这个不太好，这个placeholder不能跟随滚动，或者在占位文字多的情况下，调整contentSize
        UIColor *placeholderColor = self.placeholderColor;
        if (!placeholderColor) {
            placeholderColor = [UIColor colorWithRed:0.830 green:0.828 blue:0.865 alpha:1.000];
        }
        UIFont *font = self.font;
        if (!font) {
            font = [UIFont systemFontOfSize:16.0f];
        }
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.alignment = self.textAlignment;
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        [self.placeholder drawInRect:CGRectMake(self.contentInset.left+self.textContainerInset.left+5, self.contentInset.top+self.textContainerInset.top, self.frame.size.width-self.contentInset.left-self.textContainerInset.left-5, self.frame.size.height-self.contentInset.top-self.textContainerInset.top) withAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:placeholderColor, NSParagraphStyleAttributeName:paragraphStyle}];
    }
}

- (UIColor *)placeholderColor
{
    return objc_getAssociatedObject(self,&placeholderColorForTextViewKey);
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    static NSString * key = @"placeholderColor";
    
    [self willChangeValueForKey:key];
    objc_setAssociatedObject(self, &placeholderColorForTextViewKey, placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:key];
    
    [self setNeedsDisplay];
}

- (UIColor *)placeholder
{
    return objc_getAssociatedObject(self,&placeholderForTextViewKey);
}

- (void)setPlaceholder:(NSString *)placeholder
{
    static NSString * key = @"placeholder";
    
    [self willChangeValueForKey:key];
    objc_setAssociatedObject(self, &placeholderForTextViewKey, placeholder, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self didChangeValueForKey:key];
    
    [self setNeedsDisplay];
}

@end
